import React from 'react'
import { Form, Input, Modal } from 'antd';

export default function PasswordForm({ open, onCreate, onCancel,userRole }) {
  const [form] = Form.useForm();

  const SpecialCharsValidator = (rule, value, callback) => {
    const regex = /[ `!#$%^&*()_+\-=\\[\]{};':"\\|,<> \\/?~]/
    if (regex.test(value)) {
      callback('输入不能包含特殊字符！');
    } else {
      callback();
    }
  };

  const checkLength = (_,value) => {
    if( value && value.length < 6){
      return Promise.reject("密码最短为6位")
    }else if(value && value.length > 20) {
      return Promise.reject("密码最长一应为20位")
    }
    return Promise.resolve()
  }

  const checkPassword = (_,value) =>{
    if(value !== userRole.fd_password){
      return Promise.reject("密码不正确")
    }
    return Promise.resolve();
  }

  const checkOldTONew = (_ ,value) =>{
    if (value && value !== form.getFieldValue('newPassword')) {
      return Promise.reject(new Error('两次输入的密码不一致'));
    }
    return Promise.resolve();
  }


  const passwords = [
    { name: "oldPassword", label: "旧密码", rules: {SpecialCharsValidator,checkPassword}, labelspan: 4, labelOffset: 4, },
    { name: "newPassword", label: "新密码", rules: {SpecialCharsValidator,checkLength}, labelspan: 4, labelOffset: 4, },
    { name: "confirmPassword", label: "确认密码", rules: {SpecialCharsValidator,checkOldTONew,checkLength}, labelspan: 4, labelOffset: 4, },
  ]
  return (
    <Modal
      open={open}
      okText="提交"
      cancelText="退出"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="修改密码"
        name="passwords"
        wrapperCol={{
          span: 12,
        }}
        className="updata-user-infor"
      >
        {
          passwords.map((item) => {
            return (
              <Form.Item
                key={item.name}
                name={item.name}
                label={item.label}
                rules={[
                  {
                    required: true,
                    message: `请输入${item.label}`,
                  },
                  { validator:item.rules.SpecialCharsValidator},
                  { validator:item.rules.checkPassword},
                  { validator:item.rules.checkOldTONew},
                  { validator:item.rules.checkLength},
                ]}
                labelCol={{
                  span: item.labelspan,
                  offset: item.labelOffset
                }}
              >
                <Input.Password />
              </Form.Item>
            )
          })
        }
      </Form>
    </Modal>
  )
}
